package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.JsonUtil;
import com.cz.nongyetongv5.bean.PatrolDetailBean;
import com.cz.nongyetongv5.bean.PatrolList;
import com.cz.nongyetongv5.bean.PatrolListBean;
import com.cz.nongyetongv5.bean.PatrolListResponse;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class PatrolListActivity extends Activity implements View.OnClickListener {
    private RelativeLayout btnBack;
    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;
    private int page = 1;
    private int size = 10;
    private String add_user;
    private String regions;
    private String region_code;
    private boolean isShowEdit = false;


    private TextView tv_right;


    private int index = 1;


    private LinearLayout ll_bottom;


    private PatrolListResponse patrolListResponse;
    private PatrolListBean patrolListBean;
    private List<PatrolList> patrolLists;

    private PatrolListAdapter adapter;

    private TextView tv_pass;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol_list);
        btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshLayout);
        add_user = getIntent().getStringExtra("add_user");
//        regions = getIntent().getStringExtra("regions");
        region_code = getIntent().getStringExtra("region_code");

        tv_right = findViewById(R.id.tv_right);
        tv_right.setOnClickListener(this);
        ll_bottom = findViewById(R.id.ll_bottom);
        tv_pass = findViewById(R.id.tv_pass);

        tv_pass.setOnClickListener(this);


        patrolLists = new ArrayList<>();
        adapter = new PatrolListAdapter();
        View notDataView = getLayoutInflater().inflate(R.layout.view_nodata, (ViewGroup) recyclerView.getParent(), false);
        adapter.setEmptyView(notDataView);
        recyclerView.setLayoutManager(new LinearLayoutManager(PatrolListActivity.this));
        recyclerView.setAdapter(adapter); //设置分页和下拉刷新
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setRefreshHeader(new ClassicsHeader(PatrolListActivity.this));
        //设置 Footer
        refreshLayout.setRefreshFooter(new ClassicsFooter(PatrolListActivity.this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getPatrolList();
                //                WaitDialog.ShowDialog(getActivity(),"数据加载中...");

            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (patrolListBean != null) {
                    if (page < patrolListBean.getTotal()) {
                        page++;
                        getPatrolList();
                    } else {
                        refreshLayout.finishLoadmore();
                        Toast.makeText(PatrolListActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    refreshLayout.finishLoadmore();
                    Toast.makeText(PatrolListActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }


            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                getPatrolDetail(patrolLists.get(position).getCheck_id());
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (patrolLists.get(position).isChecked()) {
                    patrolLists.get(position).setChecked(false);
                } else {
                    patrolLists.get(position).setChecked(true);
                }
                adapter.notifyDataSetChanged();
                int sum = 0;
                for (PatrolList entList : patrolLists) {
                    if (entList.isChecked()) {
                        sum++;
                    }
                }
                if (sum == patrolLists.size()) {
                    tv_right.setText("全不选");
                    index = 3;
                } else {
                    tv_right.setText("全选");
                    index = 2;
                }
            }
        });


        getPatrolList();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finish();
                break;
            case R.id.tv_right:
                if (index == 1) {
                    tv_right.setText("全选");
                    isShowEdit = true;
                    adapter.notifyDataSetChanged();
                    ll_bottom.setVisibility(View.VISIBLE);
                    index = 2;
                } else if (index == 2) {
                    tv_right.setText("全不选");
                    setSelect(true);
                    ll_bottom.setVisibility(View.VISIBLE);
                    index = 3;
                } else if (index == 3) {
                    index = 2;
                    tv_right.setText("全选");
                    ll_bottom.setVisibility(View.VISIBLE);
                    setSelect(false);
                }
                break;
            case R.id.tv_pass:
                String ids = "";
                List<PatrolList> lists = getSelected();
                if (lists.size() <= 0) {
                    Toast.makeText(PatrolListActivity.this, "没有选择数据", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < lists.size(); i++) {
                        if (i == 0) {
                            ids = lists.get(i).getCheck_id();
                        } else {
                            ids = ids + "," + lists.get(i).getCheck_id();
                        }
                    }
                    Intent intent = new Intent(PatrolListActivity.this, DialogActivity.class);
                    intent.putExtra("add_user", add_user);
                    intent.putExtra("region_code", region_code);
                    intent.putExtra("ids", ids);
                    intent.putExtra("model", "patrol");
                    startActivityForResult(intent, 9003);
                }
                break;
            default:
                break;
        }
    }

    public int getSize() {
        return patrolLists.size();
    }

    public void setSelect(boolean isSelect) {
        for (PatrolList patrolList : patrolLists) {
            patrolList.setChecked(isSelect);
        }
        adapter.notifyDataSetChanged();
    }


    /**
     * 获取选中的item
     *
     * @return
     */
    public List<PatrolList> getSelected() {
        List<PatrolList> selectedItems = new ArrayList<>();
        for (PatrolList patrolList : patrolLists) {
            if (patrolList.isChecked()) {
                selectedItems.add(patrolList);
            }
        }
        return selectedItems;
    }


    void getPatrolDetail(String id) {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "check/checkCheckDetail.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("check_id", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        System.out.println(response);

                        Gson gson = new Gson();
                        PatrolDetailBean patrolDetailBean = gson.fromJson(response, PatrolDetailBean.class);
                        //                        EntDetailBean entDetailBean = JsonUtil.toObject(response, EntDetailBean.class);
                        if (patrolDetailBean.getCode() == 0) {
                            if (patrolDetailBean.getData() != null) {
                                Intent intent = new Intent(PatrolListActivity.this, PatrolDetailActivity.class);
                                intent.putExtra("add_user", add_user);
                                intent.putExtra("region_code", region_code);
                                intent.putExtra("patrolBean", patrolDetailBean.getData());
                                startActivity(intent);
                            } else {
                                Toast.makeText(PatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(PatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    void getPatrolList() {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "check/suspiciousCheckList.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(size))
                .addParams("region_code", region_code)
                .addParams("is_operate", String.valueOf("1"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        closeRefresh();
                        Toast.makeText(PatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response);
                        closeRefresh();
                        patrolListResponse = JsonUtil.toObject(response, PatrolListResponse.class);
                        if (patrolListResponse.getCode() == 0) {
                            patrolListBean = patrolListResponse.getData();
                            if (page == 1) {
                                patrolLists.clear();
                                patrolLists.addAll(patrolListBean.getRows());
                            } else {
                                patrolLists.addAll(patrolListBean.getRows());
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(PatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    public class PatrolListAdapter extends BaseQuickAdapter<PatrolList, BaseViewHolder> {
        public PatrolListAdapter() {
            super(R.layout.patrol_list_item, patrolLists);
        }

        @Override
        protected void convert(BaseViewHolder helper, PatrolList item) {
            if (item.getType() != null && item.getType().equals("1")) {
                helper.setText(R.id.tv_patrol_addr, "巡查对象:");
                helper.setText(R.id.tv_record_hit, "巡查内容:");
                if (item.getCheck_address() != null) {
                    helper.setText(R.id.tv_product_name, item.getEnt_name());
                } else {
                    helper.setText(R.id.tv_product_name, "--");
                }

                if (item.getContent() != null) {
                    helper.setText(R.id.tv_record, item.getContent());
                } else {
                    helper.setText(R.id.tv_record, "--");
                }
            } else {
                helper.setText(R.id.tv_patrol_addr, "巡查地点:");
                helper.setText(R.id.tv_record_hit, "巡查记录:");
                if (item.getCheck_address() != null) {
                    helper.setText(R.id.tv_product_name, item.getCheck_address());
                } else {
                    helper.setText(R.id.tv_product_name, "--");
                }

                if (item.getCheck_record() != null) {
                    helper.setText(R.id.tv_record, item.getCheck_record());
                } else {
                    helper.setText(R.id.tv_record, "--");
                }


            }

            if (item.getRealname() != null) {
                helper.setText(R.id.tv_admin, item.getRealname() + "(" + item.getRegion_name() + ")");
            }
            if (item.getCheck_time() != null) {
                helper.setText(R.id.tv_date, item.getCheck_time());
            }


            if (isShowEdit) {
                helper.setVisible(R.id.cb_choose, true);
            } else {
                helper.setVisible(R.id.cb_choose, false);
            }
            helper.addOnClickListener(R.id.cb_choose);
            helper.setChecked(R.id.cb_choose, item.isChecked());
            Glide.with(PatrolListActivity.this)
                    .load(item.getAttach_url()).placeholder(R.drawable.loading).error(R.mipmap.ic_launcher)
                    .into((ImageView) helper.getView(R.id.iv_iv));

        }
    }

    public void closeRefresh() {
        if (refreshLayout != null) {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh();
            } else if (refreshLayout.isLoading()) {
                refreshLayout.finishLoadmore();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 9003:
                    index = 1;
                    tv_right.setText("处理");
                    isShowEdit = false;
                    ll_bottom.setVisibility(View.GONE);
                    page = 1;
                    getPatrolList();
                    break;
                default:
                    break;

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        //        index = 1;
        //        tv_right.setText("处理");
        //        isShowEdit = false;
        //        ll_bottom.setVisibility(View.GONE);
        page = 1;
        getPatrolList();
    }
}
